
const { env } = require('../util/sql')
const mysql = require('mysql')
const { status200, status500 } = require('./status')


/* 分解请求头 */
const filterQuery = (e) => {
    let objs = {};
    for (let keys in e) {
        if (e[keys] != "" && e[keys] != undefined && e[keys] != null) {
            objs[keys] = e[keys];
        }
    }
    return Object.keys(objs);
}


/* 拼装sql查询 */
const assemQuery = (sql, keys) => {
    keys.forEach((ele, index) => {
        if (index != keys.length - 1) {
            sql += ele + ' = ? and '
        }
        else {
            sql += ele + ' = ? '
        }
    })
    return Promise.resolve({ sql: sql })
}

const assemArrays = (keys, req) => {
    let arr = []
    keys.forEach((el, ind) => {
        arr.push(req[el])
    })
    return Promise.resolve(arr)
}

/* 模糊查询 */
let sql = 'select * from usertest where '
const vagFind = (keys, query) => {
    keys.forEach((el, i) => {
        if (i != keys.length - 1) {
            sql += el + ` = %${query[el]}% and `
        }
        else {
            sql += el + ` = %${query[el]}% `
        }
    })
    console.log(sql,'sql')
}



/* 全部查询 */
const queryData = (sql, req, res) => {
    let pool = mysql.createPool(env)
    let pageSize = Number(req.query["pageSize"]);
    let offset = (Number(req.query["pageNo"]) - 1) * pageSize;
    pool.query(sql, [offset, pageSize], (err, result) => {
        try {
            console.log(result, '000')
            status200(res, { data: { data: result[0], total: result[1][0]['count(*)'] } })
        } catch {
            status500(res, {})
        }
    })
}

/* 精确查询 */
const accData = (sql, arr, req, res) => {
    let pool = mysql.createPool(env)
    pool.query(sql, arr, (err, result) => {
        try {
            status200(res, { data: { data: result, total: result.length } })
        } catch {
            status500(res, {})
        }
    })
}

module.exports = {
    filterQuery,
    queryData,
    assemQuery,
    assemArrays,
    accData,
    vagFind
}